import React, { Component } from 'react'
import PropTypes from "prop-types";
import PubSub from "pubsub-js";
import "./index.css";

export default class List extends Component {

  state = {
		list: [],
		isFirst: true, // 是否为第一次打开
		isLoading: false, // 是否处于加载中
		err: '', // 存储请求相关的错误信息
	}

  componentDidMount() {
    this.token = PubSub.subscribe('list-state', (_, stateObj) => {
      this.setState(stateObj);
    })
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.token);
  }

  render() {
    let {list, isFirst, isLoading, err} = this.state;
    return (
      <div className="list">
        {
          isFirst ? <h2>欢迎使用，请输入关键字搜索</h2> :
          isLoading ? <h2>Loading...</h2> :
          err ? <h2 style={{color: 'red'}}>{err}</h2> :
          list.map((item) => {
            return (
              <a key={item.id} className="item" href={item.html_url} target="_blank">
                <div className="head">
                  <img src={item.avatar_url} />
                </div>
                <div className="name">{item.login}</div>
              </a>
            )
          })
        }
      </div>
    )
  }
}
